<!-- 默认配置的表单 -->
<template>
  <a-spin :spinning="spinning">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="默认上游" name="defaultUpstream" style="width: 300px;">
        <SmartEnumSelect width="100%" v-model:value="form.defaultUpstream" enumName="UPSTREAM_ENUM" placeholder="上游" />
      </a-form-item>
    </a-form>
    <div>
      <a-button style="margin-right: 8px" @click="reset">重置</a-button>
      <a-button type="primary" @click="onSubmit" :loading="loading">保存</a-button>
    </div>
  </a-spin>
</template>
<script setup>
import { reactive, ref, nextTick } from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { configApi } from '/@/api/system/config-api';
import { UPSTREAM_ENUM } from '/@/constants/common-const';
import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
import { smartSentry } from '/@/lib/smart-sentry';

// 加载中
const spinning = ref(false);

// 前缀
let prefix;

async function initValue(tabValue) {
  spinning.value = true;
  let res = await configApi.getDefault();
  Object.assign(form, formDefault);
  if (res.data && !_.isEmpty(res.data)) {
    Object.assign(form, res.data);
  }
  nextTick(() => {
    formRef.value.clearValidate();
    prefix = tabValue;
    spinning.value = false;
  });
}

const formRef = ref();

const formDefault = {
  defaultUpstream: undefined,
}

let form = reactive(_.cloneDeep(formDefault));

const rules = {
  defaultUpstream: [{ required: true, message: '上游必选' }],
};

// 保存按钮加载
const loading = ref(false);

// 点击确定，验证表单
async function onSubmit() {
  // 加载中
  loading.value = true;
  try {
    await formRef.value.validateFields();
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
    // 取消加载中
    loading.value = false;
  }
}

// 保存
async function save() {
  try {
    await configApi.saveConfig(prefix, form);
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    // 取消加载中
    loading.value = false;
  }
}

// 重置
function reset() {
  Object.assign(form, formDefault);
}

defineExpose({
  initValue,
});
</script>
<style scoped lang="less"></style>